package com.orange.notificationsummary.loader;

import android.os.Handler;
import android.os.Message;

import com.orange.notificationsummary.EventTypeAndCount;
import com.orange.notificationsummary.utils.LogHelper;

public abstract class BasicLoader {
	private static final String	TAG			= "BasicLoader";

	private boolean				mRunning;
	private boolean				mCanceled;
	private boolean				mFinished;
	private String				mName;
	private int					mLoaderType	= -1;

	private static final int	HAND_DATA	= 0x1001;
	private static final int	HAND_SHOW	= 0x1002;

	public BasicLoader(String name, int type) {
		mRunning = false;
		mCanceled = false;
		mFinished = false;

		mName = (name == null ? "No name" : name);
		mLoaderType = type;
	}

	public void triggerStart() {
		Message message = Message.obtain();
		message.what = HAND_DATA;
		mHandler.sendMessage(message);
	}

	public void triggerShow() {
		LogHelper.v(TAG, "triggerShow. HAND_SHOW");
		Message message = Message.obtain();
		message.what = HAND_SHOW;
		mHandler.sendMessage(message);
	}

	public String toString() {
		return String.format("%s(type=%s)(0x%08x): running(%s), finished(%s)",
				mName, mLoaderType, hashCode(), mRunning, mFinished);
	}

	public String getName() {
		return mName;
	}

	public int getLoaderType() {
		return mLoaderType;
	}

	public boolean isFinised() {
		return mFinished;
	}

	public void stop() {
		mCanceled = true;
	}

	protected void onStart() {

	}

	protected void onFinish() {

	}

	protected abstract void loadData();

	protected abstract void showData();

	protected abstract EventTypeAndCount getEventTypeAndCount();

	boolean start() {
		if (mRunning) {
			return false;
		}
		mRunning = true;
		mCanceled = false;
		mFinished = false;
		onStart();
		runInThread();
		return true;
	}

	void finish() {
		mRunning = false;
		mFinished = true;
		onFinish();
	}

	void runInThread() {
		new Thread() {
			@Override
			public void run() {
				if (mCanceled) {
					finish();
				} else {
					loadData(); // from db
					triggerShow();
				}
			}
		}.start();
	}

	private Handler	mHandler	= new Handler() {
									private static final String	TAG	= "Handler";

									@Override
									public void handleMessage(Message msg) {
										switch (msg.what) {
										case HAND_DATA:
											start();
											break;
										case HAND_SHOW:
											LogHelper.v(TAG, "handleMessage. ");
											showData();
											finish();
											break;
										default:
											break;
										}
										super.handleMessage(msg);
									}
								};
}
